import { store } from "@/store";
import { usePermissionStoreHook } from "@/store/modules/permission.store";
import { useDictStoreHook } from "@/store/modules/dict.store";
import AuthAPI from "@/api/auth.api";
import UserAPI from "@/api/system/user.api";
import { setAccessToken, setRefreshToken, getRefreshToken, clearToken } from "@/utils/auth";

export const useUserStore = defineStore("user", () => {
  const userInfo = useStorage("userInfo", {});

  /**
   * 登录
   *
   * @param {Object} LoginFormData
   * @returns
   */
  function login(LoginFormData) {
    return new Promise((resolve, reject) => {
      AuthAPI.login(LoginFormData)
        .then((data) => {
          const { accessToken, refreshToken } = data;
          setAccessToken(accessToken);
          setRefreshToken(refreshToken);
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  /**
   * 更新用户头像
   *
   * @param {string} newAvatarPath 新的头像路径
   */
  function updateAvatar(newAvatarPath) {
    return new Promise((resolve) => {
      // 立即更新本地存储的头像路径
      userInfo.value.avatar = newAvatarPath;
      resolve();
    });
  }

  /**
   * 获取用户信息
   *
   * @returns {Object} 用户信息
   */
  function getUserInfo() {
    return new Promise((resolve, reject) => {
      UserAPI.getInfo()
        .then((data) => {
          if (!data) {
            reject("Verification failed, please Login again.");
            return;
          }
          
          // 保留原有的头像（如果存在），避免上传后重新获取覆盖
          const currentAvatar = userInfo.value.avatar;
          
          Object.assign(userInfo.value, { ...data });
          
          userInfo.value = {
            id: userInfo.value.id,
            username: userInfo.value.username,
            nickname: userInfo.value.username,
            avatar: currentAvatar || userInfo.value.avatar, // 优先使用当前头像
            role: userInfo.value.username,
            introduction: userInfo.value.introduction,
          };
          
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  /**
   * 登出
   */
  function logout() {
    return new Promise((resolve, reject) => {
      AuthAPI.logout()
        .then(() => {
          clearSessionAndCache();
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  /**
   * 刷新 token
   */
  function refreshToken() {
    const refreshToken = getRefreshToken();
    return new Promise((resolve, reject) => {
      AuthAPI.refreshToken(refreshToken)
        .then((data) => {
          const { accessToken, refreshToken } = data;
          setAccessToken(accessToken);
          setRefreshToken(refreshToken);
          resolve();
        })
        .catch((error) => {
          console.log(" refreshToken  刷新失败", error);
          reject(error);
        });
    });
  }

  /**
   * 清除用户会话和缓存
   */
  function clearSessionAndCache() {
    return new Promise((resolve) => {
      clearToken();
      usePermissionStoreHook().resetRouter();
      useDictStoreHook().clearDictCache();
      userInfo.value = {};
      resolve();
    });
  }

  return {
    userInfo,
    getUserInfo,
    login,
    logout,
    clearSessionAndCache,
    refreshToken,
    updateAvatar, // 导出新添加的方法
  };
});

/**
 * 用于在组件外部使用 Pinia 提供的 store 实例
 */
export function useUserStoreHook() {
  return useUserStore(store);
}